import {getWy} from '@/uni_modules/wy-core/context' 
const state={
	wssConnected:false, //是否连接
	wssFailTime:0, //错误时间
	wssPingUnix:0,//最近一次ping时间
	wssSendList:[], //发送列表
	wssPongOpen:false, //是否自动响应pong
	wssPongTimes:0, //pong时间
	wssNoticeModel:{  //消息通知数量
		message:{
			count:0,
			list:[]
		}
	}
};
const getters={
	WssConnected:state=>{
		return state.wssConnected
	},
	MessageCount:state=>{
		let res=0
		let {message}=state.wssNoticeModel
		if(message){
			let {count}=message
			if(count){
				res=parseInt(count)
			}
		}
		return res
	}
};
const mutations={
	setMessageCount(state){
        state.wssNoticeModel.message.count=0
    },
    wssPongOpen(state,data){
        state.wssPongOpen=data
    },
    wssConnected(state,data){
        state.wssConnected=data
    },
    wssFailTime(state,data){
        state.wssFailTime=data
    },
    wssPingUnix(state,data){
        state.wssPingUnix=data
    },
    wssNoticeModel(state,data){
        state.wssNoticeModel=data
    },
    wssSendList(state,data){
        state.wssSendList=data
    },
    wssSendListPush(state,data){
        state.wssSendList.push(data)
    }
};
const actions={
	setMessageCount({commit}){
		let {message}=state.wssNoticeModel
		if(message){
			let {count}=message
            commit('setMessageCount',count)
			
		}
	},
	heartbit({dispatch,commit}){
		state.wssPongTimes++
        let wy=getWy()
        let {heartbit,heartbit_data}=wy.config.Sys.wss
		if(state.wssConnected){
			dispatch('send',heartbit_data) 
            wy.publish(pubkey,{event:'onHeartbit',data:heartbit_data}) 
		} 
		if(heartbit){
		    setTimeout(function(){
		    	dispatch('heartbit',heartbit_data)
		    },heartbit*1000)
		}
	},
    close({state,commit}){
        if(state.wssConnected){
            uni.closeSocket({
                success() {
                    commit('wssConnected',false)
                }
            })
        }
    },
    open({dispatch,state,commit},option){
        return new Promise((resolve, reject)=>{
            if(state.wssConnected){
                resolve()
            }
            else{
               let {onSocketMessage,onSocketOpen,onSocketError}=option
               let wy=getWy() 
               let {host,auto_pong,ping_data,pong_data,retry_limit,heartbit,retry_second,pubkey}=wy.config.Sys.wss
               uni.onSocketOpen((res) => {
                   console.log('SocketOpen')
                   commit('wssFailTime',0)
                   commit('wssConnected',true)
                   wy.publish(pubkey,{event:'onSocketOpen',data:res})  
                   if(heartbit){ 
                       setTimeout(function(){
                           dispatch('heartbit')
                       },heartbit*1000)
                   }
                    if(onSocketOpen){
                      onSocketOpen(true)
                    }
               })
               uni.onSocketError((err) => { 
                    commit('wssFailTime',state.wssFailTime+1) 
                    wy.publish(pubkey,{event:'onSocketError',data:err}) 
                    if(retry_limit>0 && state.wssFailTime>retry_limit){ 
                       wy.publish(pubkey,{event:'onSocketExit',data:'wss服务重连超过最大次数'}) 
                       console.log('连接失败，可能是websocket服务不可用!')
                    }
                    else{
                        console.log('onError', err);
                        setTimeout(function(){
                            dispatch('open')
                        },retry_second*1000)
                    }
                   if(onSocketError){
                       onSocketError(err)
                   }
               })
               uni.onSocketMessage((res) => {
                   if(onSocketMessage){
                       onSocketMessage(res)
                   }
                   if(res == ping_data && auto_pong){ 
                       dispatch('send',{message:pong_data})
                   } 
                   wy.publish(pubkey,{event:'onSocketMessage',data:res}) 
               })
               uni.onSocketClose((res) => {
                   wy.publish(pubkey,{event:'onSocketClose',data:res})
                   commit('wssConnected',false) 
               })
               uni.connectSocket({
               	url: host,
               	data() {
               		return {
               			//content:''
               		}
               	},
               	// #ifdef MP
               	header: {
               		'content-type': 'application/json'
               	},
               	// #endif
               	// #ifdef MP-WEIXIN
               	method: 'GET',
               	// #endif
               	success(res) {
               		// 这里是接口调用成功的回调，不是连接成功的回调，请注意
                    resolve(res)
               	},
               	fail(err) {
               		// 这里是接口调用失败的回调，不是连接失败的回调，请注意
                    reject(err)
               	}
               }) 
            }
            
        })
        
	},
	loginWebSocket({dispatch},option){
		let {sid}=option
		let data={
			type:'login',
			client_name:sid,
			room_id:wy.config.App.sitekey//Sys.wss.room_id
		}
		dispatch('send',data)
	},
	sendList({state,dispatch,commit}){
		if(state.wssConnected){
			let list=state.wssSendList 
            commit('wssSendList',[])
			for(let i=0;i<list.length;i++){
				dispatch('send',list[i])
			}
		}
	},
	send({state},{message,success,fail}) {
		if(state.wssConnected){ 
			uni.sendSocketMessage({
				data: message,
				success(res) {
                    success && success(res)
//					console.log(res);
				},
				fail(err) {
                    fail && fail({type:'error',data:err})
				}
			})
		}else{
            fail && fail({type:'connected',data:'不在线'})
            commit('wssSendListPush',data) 
		}
		
	},
	
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}